package com.ouc.eddyAlgorithm.service.impl;

import com.ouc.common.utils.DateUtils;
import com.ouc.common.utils.TextUtils;
import com.ouc.eddyAlgorithm.domain.VgA4b3Track;
import com.ouc.eddyAlgorithm.mapper.VgA4b3TrackMapper;
import com.ouc.eddyAlgorithm.service.IVgA4b3TrackService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.File;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 涡旋跟踪Service业务层处理
 *
 * @author ouc
 * @date 2024-08-10
 */
@Service
public class VgA4b3TrackServiceImpl implements IVgA4b3TrackService {
  @Autowired
  private VgA4b3TrackMapper vgA4b3TrackMapper;

  /**
   * 查询涡旋跟踪
   *
   * @param id 涡旋跟踪主键
   * @return 涡旋跟踪
   */
  @Override
  public VgA4b3Track selectVgA4b3TrackById(Integer id) {
    return vgA4b3TrackMapper.selectVgA4b3TrackById(id);
  }

  /**
   * 查询涡旋跟踪列表
   *
   * @param vgA4b3Track 涡旋跟踪
   * @return 涡旋跟踪
   */
  @Override
  public List<VgA4b3Track> selectVgA4b3TrackList(VgA4b3Track vgA4b3Track) {
    return vgA4b3TrackMapper.selectVgA4b3TrackList(vgA4b3Track);
  }

  /**
   * 新增涡旋跟踪
   *
   * @param vgA4b3Track 涡旋跟踪
   * @return 结果
   */
  @Override
  public int insertVgA4b3Track(VgA4b3Track vgA4b3Track) {
    return vgA4b3TrackMapper.insertVgA4b3Track(vgA4b3Track);
  }

  /**
   * 修改涡旋跟踪
   *
   * @param vgA4b3Track 涡旋跟踪
   * @return 结果
   */
  @Override
  public int updateVgA4b3Track(VgA4b3Track vgA4b3Track) {
    return vgA4b3TrackMapper.updateVgA4b3Track(vgA4b3Track);
  }

  /**
   * 批量删除涡旋跟踪
   *
   * @param ids 需要删除的涡旋跟踪主键
   * @return 结果
   */
  @Override
  public int deleteVgA4b3TrackByIds(Integer[] ids) {
    return vgA4b3TrackMapper.deleteVgA4b3TrackByIds(ids);
  }

  /**
   * 删除涡旋跟踪信息
   *
   * @param id 涡旋跟踪主键
   * @return 结果
   */
  @Override
  public int deleteVgA4b3TrackById(Integer id) {
    return vgA4b3TrackMapper.deleteVgA4b3TrackById(id);
  }

  //向前跟踪，时间，经纬度
  @Override
  public int vgEddyTrack(String startTime, String endTime, Float startLat, Float endLat, Float startLon, Float endLon, int trackTime, int trackLevel, float trackNum) throws ParseException {
    int updateNum = 0;
    Calendar calendar = new GregorianCalendar();
    String formatType = "yyyy-MM-dd";
    SimpleDateFormat formatter = new SimpleDateFormat(formatType);
    Date startData = formatter.parse(startTime);
    Date endData = formatter.parse(endTime);
    Date date = startData;
    while (date.compareTo(endData) <= 0) { //更新当前时间的涡旋
      //查询当前时间的涡旋
      VgA4b3Track vgA4b3Track = new VgA4b3Track();
      Map<String, Object> params = new HashMap<>();
      params.put("beginDate", formatter.format(date));
      params.put("endDate", formatter.format(date));
      if (startLat != null) {
        params.put("beginLat", startLat);
      }
      if (endLat != null) {
        params.put("endLat", endLat);
      }
      if (startLon != null) {
        params.put("beginLon", startLon);
      }
      if (endLon != null) {
        params.put("endLon", endLon);
      }
      vgA4b3Track.setParams(params);
      List<VgA4b3Track> vgA4b3TrackList = vgA4b3TrackMapper.selectVgA4b3TrackOrderById(vgA4b3Track);
      //查询前trackTime天的涡旋
      calendar.setTime(date);
      calendar.add(calendar.DATE, -trackTime);
      Date dateStart = calendar.getTime();
//      calendar.setTime(date);
//      calendar.add(calendar.DATE, -1);
//      Date dateEnd = calendar.getTime();
      Date dateEnd = date;

      for (int i = 0; i < vgA4b3TrackList.size(); i++) {
        VgA4b3Track vgEddy = vgA4b3TrackList.get(i);
        VgA4b3Track vgEddySelect = new VgA4b3Track();
        Map<String, Object> paramsSelect = new HashMap<>();

        paramsSelect.put("beginDate", formatter.format(dateStart));
        paramsSelect.put("endDate", formatter.format(dateEnd));
//        paramsSelect.put("beginLat", vgEddy.getLat().floatValue() - trackNum);
//        paramsSelect.put("endLat", vgEddy.getLat().floatValue() + trackNum);
//        paramsSelect.put("beginLon", vgEddy.getLon().floatValue() - trackNum);
//        paramsSelect.put("endLon", vgEddy.getLon().floatValue() + trackNum);
        paramsSelect.put("beginLevel", vgEddy.getLevel().intValue() - trackLevel);
        paramsSelect.put("endLevel", vgEddy.getLevel().intValue());
        int detNum = (int) (trackNum * 12 + 0.5);
        paramsSelect.put("beginI", vgEddy.getI() - detNum);
        paramsSelect.put("endI", vgEddy.getI() + detNum);
        paramsSelect.put("beginJ", vgEddy.getJ() - detNum);
        paramsSelect.put("endJ", vgEddy.getJ() + detNum);

        vgEddySelect.setParams(paramsSelect);
        List<VgA4b3Track> vgEddySelectList = vgA4b3TrackMapper.selectVgA4b3TrackList(vgEddySelect);

        Integer upId = null;
        if (vgEddySelectList.size() > 0) {
          int temp = 0;
          for (int j = 1; j < vgEddySelectList.size(); j++) {
//            if (Math.abs(vgEddySelectList.get(j).getLevel() - vgEddySelectList.get(temp).getLevel()) < trackLevel) {
            if (vgEddySelectList.get(j).getDate().compareTo(vgEddySelectList.get(temp).getDate()) < 0) {
              temp = j;
            } else if (vgEddySelectList.get(j).getDate().compareTo(vgEddySelectList.get(temp).getDate()) == 0 &&
                vgEddySelectList.get(j).getLevel() < vgEddySelectList.get(temp).getLevel()) {
              temp = j;
            }
          }
//          }
          upId = vgEddySelectList.get(temp).getTrack();
          if (upId == null) {
            upId = vgEddySelectList.get(temp).getId();
          }
        } else {
          upId = vgEddy.getTrack();
          if (upId == null) {
            upId = vgEddy.getId();
          }
        }
        if (!upId.equals(vgEddy.getTrack())) {
          VgA4b3Track vgEddyUpdate = new VgA4b3Track();
          vgEddyUpdate.setId(vgEddy.getId());
          vgEddyUpdate.setTrack(upId);
          vgA4b3TrackMapper.updateVgA4b3Track(vgEddyUpdate);
//          updateNum++;
        }
        updateNum++;
      }

      calendar.setTime(date);
      calendar.add(calendar.DATE, 1); //把日期往后增加一天,整数  往后推,负数往前移动
      date = calendar.getTime(); //这个时间就是日期往后推一天的结果
    }

    System.out.println("共更新涡旋轨迹数目 = " + updateNum);
    return updateNum;
  }

  /**
   * 查询涡旋跟踪列表(预报数据，1天)
   *
   * @param vgA4b3Track 涡旋跟踪
   * @return 涡旋跟踪
   */
  @Override
  public List<VgA4b3Track> selectVgA4b3TrackByForecast(VgA4b3Track vgA4b3Track) {
    return vgA4b3TrackMapper.selectVgA4b3TrackByForecast(vgA4b3Track);
  }


  @Override
  public int insertVgForecast(VgA4b3Track vgA4b3Track) {
    return vgA4b3TrackMapper.insertVgForecast(vgA4b3Track);
  }


  @Override
  public int deleteTodayEddy(Date today) {
    VgA4b3Track vgA4b3Track = new VgA4b3Track();
    Map<String, Object> params = new HashMap<>();
    params.put("beginDate", DateUtils.parseDateToStr("yyyy-MM-dd", today));
    Date date = DateUtils.addDays(today, 10);
    params.put("endDate", DateUtils.parseDateToStr("yyyy-MM-dd", date));
    vgA4b3Track.setParams(params);
    List<VgA4b3Track> vgA4b3TrackList = vgA4b3TrackMapper.selectVgA4b3TrackList(vgA4b3Track);
    Integer[] ids = new Integer[vgA4b3TrackList.size()];
    for (int i = 0; i < vgA4b3TrackList.size(); i++) {
      ids[i] = vgA4b3TrackList.get(i).getId();
    }
    vgA4b3TrackMapper.deleteVgA4b3TrackByIds(ids);

    return vgA4b3TrackList.size();
  }

  @Override
  public String vgToJson(String time) throws ParseException {
    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd");
    Date date = dateFormat.parse(time);
    VgA4b3Track vgA4b3Track = new VgA4b3Track();
    Map<String, Object> params = new HashMap<>();
    params.put("beginDate", DateUtils.parseDateToStr("yyyy-MM-dd", date));
    params.put("endDate", DateUtils.parseDateToStr("yyyy-MM-dd", date));
    vgA4b3Track.setParams(params);
    List<VgA4b3Track> vgA4b3TrackList = vgA4b3TrackMapper.selectVgA4b3TrackList(vgA4b3Track);

    Date today = DateUtils.parseDate(DateUtils.getDate());
    String todayString = DateUtils.parseDateToStr("yyyyMMdd", today);
    String outFilePath = "D:\\mydatabase\\vortex\\" + todayString + "\\" + "vortex_" + time + "00.txt";

    eddyListToJson(outFilePath, vgA4b3TrackList, time);

    System.out.println(outFilePath);

    return outFilePath;
  }

  @Override
  public String vgTrackToJson(Integer track) {
    VgA4b3Track vgA4b3Track = new VgA4b3Track();
    vgA4b3Track.setTrack(track);
    List<VgA4b3Track> vgA4b3TrackList = vgA4b3TrackMapper.selectVgA4b3TrackList(vgA4b3Track);

    Date today = DateUtils.parseDate(DateUtils.getDate());
    String time = DateUtils.parseDateToStr("yyyyMMdd", today);
    String outFilePath = "D:\\mydatabase\\vortex\\" + time + "\\" + "trackVortex_" + track + ".txt";
    eddyListToJson(outFilePath, vgA4b3TrackList, time);
    System.out.println("已生成涡旋跟踪json文件，目录：" + outFilePath);

    return outFilePath;
  }

  private void eddyListToJson(String outFilePath, List<VgA4b3Track> vgA4b3TrackList, String time) {
    File file = new File(outFilePath);
    if (!file.getParentFile().exists()) {
      file.getParentFile().mkdirs();
    }

    StringBuilder sb = new StringBuilder();
    sb.append("{");
    sb.append("\"time\":\"" + time).append("\",");
    sb.append("\"startLon\":\"-180\",");
    sb.append("\"endLon\":\"180\",");
    sb.append("\"startLat\":\"-80\",");
    sb.append("\"endLat\":\"90\",");
    sb.append("\"num\":\"" + vgA4b3TrackList.size() + "\",");
    int num = vgA4b3TrackList.size();

    sb.append("\"id\":[");
    for (int i = 0; i < num; i++) {
      if (i == 0) {
        sb.append("\"" + vgA4b3TrackList.get(i).getId() + "\"");
      } else {
        sb.append(",\"" + vgA4b3TrackList.get(i).getId() + "\"");
      }
    }
    sb.append("],");

    sb.append("\"track\":[");
    for (int i = 0; i < num; i++) {
      if (i == 0) {
        sb.append("\"" + vgA4b3TrackList.get(i).getTrack() + "\"");
      } else {
        sb.append(",\"" + vgA4b3TrackList.get(i).getTrack() + "\"");
      }
    }
    sb.append("],");

    sb.append("\"type\":[");
    for (int i = 0; i < num; i++) {
      if (i == 0) {
        sb.append("\"" + vgA4b3TrackList.get(i).getType() + "\"");
      } else {
        sb.append(",\"" + vgA4b3TrackList.get(i).getType() + "\"");
      }
    }
    sb.append("],");

    sb.append("\"lat\":[");
    for (int i = 0; i < num; i++) {
      if (i == 0) {
        sb.append("\"" + vgA4b3TrackList.get(i).getLat() + "\"");
      } else {
        sb.append(",\"" + vgA4b3TrackList.get(i).getLat() + "\"");
      }
    }
    sb.append("],");

    sb.append("\"lon\":[");
    for (int i = 0; i < num; i++) {
      if (i == 0) {
        sb.append("\"" + vgA4b3TrackList.get(i).getLon() + "\"");
      } else {
        sb.append(",\"" + vgA4b3TrackList.get(i).getLon() + "\"");
      }
    }
    sb.append("],");

    sb.append("\"date\":[");
    for (int i = 0; i < num; i++) {
      if (i == 0) {
        sb.append("\"" + DateUtils.parseDateToStr("yyyy-MM-dd", vgA4b3TrackList.get(i).getDate()) + "\"");
      } else {
        sb.append(",\"" + DateUtils.parseDateToStr("yyyy-MM-dd", vgA4b3TrackList.get(i).getDate()) + "\"");
      }
    }
    sb.append("],");

    sb.append("\"radius\":[");
    for (int i = 0; i < num; i++) {
      if (i == 0) {
        sb.append("\"" + vgA4b3TrackList.get(i).getRadius() + "\"");
      } else {
        sb.append(",\"" + vgA4b3TrackList.get(i).getRadius() + "\"");
      }
    }
    sb.append("]");

    sb.append("}");
    TextUtils.txtWrite(sb.toString(), outFilePath);
    return;
  }

}
